import Vue from 'vue'
import vueResource from 'vue-resource'
import { Promise } from 'es6-promise'
import FastClick  from 'fastclick'



Vue.use(vueResource)
/**
 * 添加fastClick
 */
FastClick.attach(document.body)
/**
日期格式化函数
@param  {DateString}  timestamp default: 当前时间
@param  {formatString} fmt  default: yyyy-mm-dd  y:年 m:月 d:日 w:星期 h:小时 M:分钟 s:秒
**/
exports.dateFormat = function(timestamp,fmt) {
    let D = new Date(),
         week = '日一二三四五六';
    timestamp && D.setTime(timestamp);
    fmt = fmt || 'yyyy-mm-dd';
    let d = {
        'm+': D.getMonth() + 1,
        'd+': D.getDate(),
        'w+': week.charAt(D.getDay()),
        'h+': D.getHours(),
        'M+': D.getMinutes(),
        's+': D.getSeconds()
    };
    if(/(y+)/.test(fmt)){
        fmt = fmt.replace(RegExp.$1,(D.getFullYear()+'').slice(-RegExp.$1.length));
    }
    Object.keys(d).forEach((key)=>{
        if(new RegExp(`(${key})`).test(fmt)){
            fmt = fmt.replace(RegExp.$1,(RegExp.$1.length === 1) ? d[key] : (`00${d[key]}`).slice((''+d[key]).length));
        }
    });
    return fmt;
}

// 检查是否是登录
exports.isLogined = function() {
    var sessionLoginId = sessionStorage.getItem('loginId');
    return !!sessionLoginId;
}


// 返回loginId
exports.getLoginId = function(){
    var sessionLoginId = sessionStorage.getItem('loginId');
    if(!sessionLoginId){
        return {
            state:false,
            data:null
        }
    }else{
        return {
            state:true,
            data:sessionLoginId
        }
    }
}

/**
 * 异步加载库，post异步请求封装
 * @url  {[string]} url   [请求接口路径]
 * @param  {[Object]} param [请求参数]
 * @type  {[bool]} param [true不使用util封装]
 * @return {[Object]}       [返回一个promise对象]
 */
const $post = function(url, param,type) {
    if(type){
        return Vue.http.post(url, param)
    }
    return new Promise((resolve, reject) => {
        Vue.http.post(url, param).then(function(res){
            if( res.data.msgCode == 100 ){
                resolve(res.data);
            }else{
                reject(res.data)
            }
        }, function(res){
            let router = window.router;
            router.app.$dispatch('alertShow',{
                tit:"温馨提示",
                val:"服务器异常"
            })
            reject(res)
        })
    })
}
    // 封装vue发出post请求
exports.$post = $post;

/**
 * 解析url
 * @param  {[type]} url [description]
 * @return {[type]}     [description]
 */
exports.parseURL = function(url) {
    var a = document.createElement('a');
    a.href = url;
    return {
        source: url,
        protocol: a.protocol.replace(':', ''),
        host: a.hostname,
        port: a.port,
        query: a.search,
        params: (function() {
            var ret = {},
                seg = a.search.replace(/^\?/, '').split('&'),
                len = seg.length,
                i = 0,
                s;
            for (; i < len; i++) {
                if (!seg[i]) {
                    continue; }
                s = seg[i].split('=');
                ret[s[0]] = s[1];
            }
            return ret;
        })(),
        file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
        hash: a.hash.replace('#', ''),
        path: a.pathname.replace(/^([^\/])/, '/$1'),
        relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
        segments: a.pathname.replace(/^\//, '').split('/')
    };
}


//出错函数
exports.ajaxError = function(res){

}


//设置修改title函数
exports.setPageTitle = function(tit,vm){
    document.title = tit
    /**
     * 微信修改title hack，仅在微信端使用
     */

    // let body = document.body;
    // var $iframe = document.createElement('iframe');
    // $iframe.style.display = "none"
    // $iframe.src = "/favicon.ico"
    // body.appendChild($iframe)
    // $iframe.onload  = function(){
    //     setTimeout(function() {
    //         $iframe.onload = null;
    //         body.removeChild($iframe)
    //     },0);
    // }
    vm.$dispatch("setTitle",document.title)

}


exports.moneyParse = function(val){
    return val/100;
}

exports.toUserLogin = function(){
    exports.$post('/basic/trip/o2o/callback',{
        "cardNo":"20160106002",
        "sId":"521376795",
        "storeId":"3313",
        "employeeName":"刘练源",
        "employeeMobile":"13570963376",
        "memberId":"27142571"
    }).then(function(res){
        var urlObj = exports.parseURL(res.result.data);
        sessionStorage.setItem('loginId',urlObj.params.id)
    },function(res){
        sessionStorage.removeItem('loginId');
    })
}